package com.card.user;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.xiaoao.net.global.Global;
import com.xiaoao.net.json.message.JsonMessage;
import com.xiaoao.net.json.message.JsonMessageCenter;

/**   
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author siyunlong  
 * @date 2016年9月24日 上午9:52:27 
 * @version V1.0   
 */
public class MessageQueue {
	private static final JsonMessage NullMessage = new JsonMessage(-1);
	private BlockingQueue<JsonMessage> messageQueue = new LinkedBlockingQueue<>();
	private MessageTask messageTask;
	private UserBase user;
	private volatile boolean isShutdown;
	
	public class MessageTask implements Runnable{
		@Override
		public void run() {
			while (!isShutdown) {
				try {
					if(messageQueue == null) {
						return;
					}
					JsonMessage message = messageQueue.take();
					if(message == NullMessage) {
						return;
					}
					if(user != null && user.getCtx() != null) {
						JsonMessageCenter.getInstance().sendMessage(message, user.getCtx());
						try {
							Thread.sleep(100L);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}else{
						return;
					}
	            } catch (Exception e) {
	            	Global.logErrorMessage(e);
	            	e.printStackTrace();
	            } 
			}
		}
    	
    }

	public MessageQueue(User user) {
		this.user = user;
		this.messageTask = new MessageTask();
        new Thread(messageTask, "MessageQueue" + this.user.getPrimaryKey()).start();
	}
	
	public void addMessage(JsonMessage message) {
		if(this.messageQueue != null) {
			messageQueue.add(message);
		}
	}
	
	public void shutdown() {
		this.isShutdown = true;
		this.messageQueue.add(NullMessage);
		this.messageQueue.add(NullMessage);
		this.user = null;
		this.messageTask = null;
	}
	
}
